<template>
  <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      label-position="left"
      label-width="100px"
      class="register-form"
  >
    <!-- 邮箱 -->
    <el-form-item label="登录邮箱" prop="email">
      <el-input
          v-model="registerForm.email"
          placeholder="请输入邮箱（可用于登录）"
          prefix-icon="Message"
          :disabled="isLoading"
      />
    </el-form-item>

    <!-- 邮箱验证码 -->
    <el-form-item label="验证码" prop="code">
      <el-row :gutter="12">
        <el-col :span="14">
          <el-input
              v-model="registerForm.code"
              placeholder="请输入验证码"
              prefix-icon="VerificationCode"
              :disabled="isLoading"
          />
        </el-col>
        <el-col :span="10">
          <el-button
              type="text"
              :disabled="isLoading || isCodeSending || !registerForm.email"
              @click="sendCode"
              class="code-btn"
          >
            {{ isCodeSending ? `${countDown}秒后重发` : "获取验证码" }}
          </el-button>
        </el-col>
      </el-row>
    </el-form-item>

    <!-- 登录用户名（新增） -->
    <el-form-item label="登录用户名" prop="username">
      <el-input
          v-model="registerForm.username"
          placeholder="请设置登录用户名（3-20字符）"
          prefix-icon="UserFilled"
          :disabled="isLoading"
      />
    </el-form-item>

    <!-- 真实姓名（原username改为name） -->
    <el-form-item label="真实姓名" prop="name">
      <el-input
          v-model="registerForm.name"
          placeholder="请输入真实姓名"
          prefix-icon="User"
          :disabled="isLoading"
      />
    </el-form-item>

    <!-- 密码 -->
    <el-form-item label="登录密码" prop="password">
      <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="请输入至少8位密码"
          prefix-icon="Lock"
          :disabled="isLoading"
          show-password
      />
    </el-form-item>

    <!-- 确认密码 -->
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          prefix-icon="Lock"
          :disabled="isLoading"
          show-password
      />
    </el-form-item>

    <!-- 住址（高德API解析） -->
    <el-form-item label="住址" prop="address">
      <el-input
          v-model="registerForm.address"
          placeholder="请输入详细住址（如：XX小区XX栋）"
          prefix-icon="Location"
          :disabled="isLoading"
          @change="handleAddressChange"
      />
      <!-- 解析结果显示 -->
      <el-tag v-if="registerForm.province" type="info" size="small" style="margin-top: 8px;">
        {{ registerForm.province }} {{ registerForm.city }} {{ registerForm.district }}
      </el-tag>
    </el-form-item>

    <!-- 手机号（可选） -->
    <el-form-item label="手机号" prop="phone">
      <el-input
          v-model="registerForm.phone"
          placeholder="请输入手机号（可选）"
          prefix-icon="Phone"
          :disabled="isLoading"
      />
    </el-form-item>

    <!-- 提交按钮 -->
    <el-form-item>
      <el-button
          type="primary"
          class="register-btn"
          :loading="isLoading"
          @click="handleRegister"
      >
        注册
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onUnmounted } from "vue";
import { ElForm, ElMessage, type FormRules } from "element-plus";
import axios from "../utils/request.ts";

// 定义注册表单数据的类型（新增username，原username改为name）
interface RegisterFormType {
  email: string;
  code: string;
  username: string; // 新增：登录用户名（表中username字段）
  name: string;     // 原username改为name：真实姓名（表中name字段）
  password: string;
  confirmPassword: string;
  address: string;
  phone: string;
  province: string;
  city: string;
  district: string;
  location: string; // 经纬度（高德原始格式：lng,lat）
}

// 组件通信：注册成功/关闭回调
const emit = defineEmits(["success", "close"]);

// 表单引用
const registerFormRef = ref<InstanceType<typeof ElForm>>();

// 加载状态
const isLoading = ref(false);
// 验证码发送状态
const isCodeSending = ref(false);
// 倒计时
const countDown = ref(60);
// 倒计时定时器
let countDownTimer: ReturnType<typeof setInterval> | null = null;

// 注册表单数据（同步类型修改）
const registerForm = reactive<RegisterFormType>({
  email: "",
  code: "",
  username: "", // 登录用户名
  name: "",     // 真实姓名
  password: "",
  confirmPassword: "",
  address: "",
  phone: "",
  // 高德API解析结果（后端验证用）
  province: "",
  city: "",
  district: "",
  location: "",
});

// 表单验证规则（新增username规则，原username规则改为name）
const registerRules = reactive<FormRules<RegisterFormType>>({
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入合法邮箱", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 6, max: 6, message: "验证码长度为6位", trigger: "blur" },
  ],
  username: [ // 新增：登录用户名验证
    { required: true, message: "请设置登录用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在3-20个字符之间", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]{3,20}$/, message: "用户名仅支持字母、数字和下划线", trigger: "blur" },
  ],
  name: [ // 原username规则改为name：真实姓名验证
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在2-20个字符之间", trigger: "blur" },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: "姓名仅支持中文和字母", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, max: 20, message: "密码长度在8-20个字符之间", trigger: "blur" },
    // 简化正则：允许大小写字母、数字、任意非空格特殊字符，且必须包含这四类中的三类？
    // 不，直接明确要求：包含大小写字母、数字、特殊字符（任意非字母数字）
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s])[^\s]{8,20}$/,
      message: "密码需包含大小写字母、数字和特殊字符（不能有空格）",
      trigger: ["blur", "input"] // 同时监听输入和失焦，实时反馈
    },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== registerForm.password) {
          callback(new Error("两次密码输入不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  address: [
    { required: true, message: "请输入住址", trigger: "blur" },
    { min: 5, message: "请输入详细住址", trigger: "blur" },
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入合法手机号（可选）",
      trigger: "blur",
      required: false,
    },
  ],
  location: [ // 新增location验证（确保地址解析成功）
    { required: true, message: "地址解析失败，请输入有效地址", trigger: "blur" },
  ],
});

// 监听地址变化，调用高德API解析（逻辑不变）
const handleAddressChange = async (val: string) => {
  if (val.length < 5) return;
  try {
    // 调用高德地理编码API（替换为你的高德Key）
    const res = await axios.get("https://restapi.amap.com/v3/geocode/geo", {
      params: {
        address: val,
        key: "15c34337dedb615e26d136476e3234c7",
        city: "西安市", // 限定城市（可选，提高解析精度）
      },
    });

    const data = res.data;
    if (data.status === "1" && data.count > "0") {
      const geocode = data.geocodes[0];
      registerForm.province = geocode.province;
      registerForm.city = geocode.city;
      registerForm.district = geocode.district;
      registerForm.location = geocode.location;
    } else {
      ElMessage.warning("地址解析失败，请输入更详细的地址");
      // 解析失败清空数据（后端会禁止注册）
      registerForm.province = "";
      registerForm.city = "";
      registerForm.district = "";
      registerForm.location = "";
    }
  } catch (error) {
    ElMessage.error("地址解析异常，请重试");
    console.error("高德API解析失败：", error);
  }
};

// 发送验证码（逻辑不变）
const sendCode = async () => {
  try {
    // 简单验证邮箱格式
    const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailReg.test(registerForm.email)) {
      ElMessage.warning("请输入合法邮箱");
      return;
    }

    // 发送验证码请求（调用后端接口）
    await axios.post("/auth/send-code", {
      email: registerForm.email,
    });

    ElMessage.success("验证码已发送至邮箱");
    isCodeSending.value = true;

    // 倒计时逻辑
    countDownTimer = setInterval(() => {
      countDown.value--;
      if (countDown.value <= 0) {
        clearInterval(countDownTimer!);
        isCodeSending.value = false;
        countDown.value = 60;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error("验证码发送失败，请重试");
    console.error("发送验证码失败：", error);
  }
};

// 处理注册（调整接口参数：新增username，原username改为name）
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  // 1. 表单验证
  const valid = await registerFormRef.value.validate();
  if (!valid) return;

  // 2. 地址解析验证（必须成功）
  if (!registerForm.location) {
    ElMessage.error("地址解析失败，请输入有效地址");
    return;
  }

  try {
    isLoading.value = true;
    // 3. 调用后端注册接口（参数同步修改：username和name分开传递）
    await axios.post("/auth/register", {
      email: registerForm.email,
      code: registerForm.code,
      username: registerForm.username, // 登录用户名
      name: registerForm.name,         // 真实姓名
      password: registerForm.password,
      address: registerForm.address,
      phone: registerForm.phone,
      province: registerForm.province,
      city: registerForm.city,
      district: registerForm.district,
      location: registerForm.location,
      role: "sales_rep", // 默认销售代表角色
    });

    // 4. 注册成功，触发回调
    emit("success");
  } catch (error: any) {
    ElMessage.error(error.response?.data?.msg || "注册失败，请重试");
    console.error("注册失败：", error);
  } finally {
    isLoading.value = false;
  }
};

// 组件卸载时清除定时器（逻辑不变）
onUnmounted(() => {
  if (countDownTimer) {
    clearInterval(countDownTimer);
  }
});
</script>

<style scoped lang="scss">
.register-form {
  padding: 10px 0;

  .code-btn {
    width: 100%;
    color: #409eff;
  }

  .register-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
  }
}
</style>